package com.open.rbac.service.sys.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import com.open.rbac.model.entity.sys.Organization;


@Transactional(rollbackFor = Exception.class)
public interface OrganizationRepository extends JpaRepository<Organization, String> {

    @Query(" SELECT t1 FROM organization t1 WHERE t1.code = ?1")
    List<Organization> findByCode(String code);


    @Query(" SELECT t1 FROM organization t1 WHERE t1.parentId = ?1")
    List<Organization> findByParentId(String id);

    @Query("""
            SELECT DISTINCT t1 FROM organization t1
            INNER JOIN organization_user_rel t2
            ON t1.id = t2.organizationId
            WHERE t2.userId IN (?1)
        """)
    List<Organization> findByUserIds(List<String> userIds);


    @Query("SELECT t1 FROM organization t1 WHERE t1.id IN (?1)")
    List<Organization> findByIds(List<String> ids);

    @Modifying
    @Query("UPDATE organization o SET o.enable = ?2 WHERE o.id = ?1")
    void updateEnable(String id, boolean enable);

}
